package com.wstuo.common.security.service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.file.csv.CSVReader;
import com.wstuo.common.file.csv.CSVWriter;
import com.wstuo.common.security.dao.ICompanyDAO;
import com.wstuo.common.security.dao.ISupplierDAO;
import com.wstuo.common.security.dto.OrganizationDTO;
import com.wstuo.common.security.dto.SupplierDTO;
import com.wstuo.common.security.dto.SupplierQueryDTO;
import com.wstuo.common.security.entity.Company;
import com.wstuo.common.security.entity.Organization;
import com.wstuo.common.security.entity.Supplier;
import com.wstuo.common.security.utils.FileEncodeUtils;
import com.wstuo.common.security.utils.LanguageContent;

/**
 * 供应商业务类.
 */
@SuppressWarnings("unchecked")
public class SupplierService implements ISupplierService {
	private final static Logger LOGGER = Logger.getLogger(SupplierService.class);
	@Autowired
	private ISupplierDAO supplierDAO;
	@Autowired
	private ICompanyDAO companyDAO;

	/**
	 * 分页查询供应商
	 * 
	 * @param supplierrQueryDTO
	 * @param sidx
	 * @param sord
	 * @return PageDTO
	 */
	public PageDTO findPagerSupplier(SupplierQueryDTO supplierrQueryDTO,
			String sidx, String sord) {
		PageDTO p = supplierDAO.findPager(supplierrQueryDTO, sidx, sord);
		List<Supplier> entities = (List<Supplier>) p.getData();
		List<SupplierDTO> dtos = new ArrayList<SupplierDTO>();
		for (Supplier sup : entities) {
			SupplierDTO dto = new SupplierDTO();
			if (sup.getParentOrg() != null) {
				dto.setCompanyNo(sup.getParentOrg().getOrgNo());
			}
			if (sup.getCompanyNo() != null && sup.getCompanyNo() != 0) {
				dto.setCompanyName(companyDAO.findById(sup.getCompanyNo())
						.getOrgName());
			}
			SupplierDTO.entity2dto(sup, dto);
			// 查找类型
			dtos.add(dto);
		}
		p.setData(dtos);
		return p;
	}

	/**
	 * dto to entity
	 */
	private void dto2entity(SupplierDTO dto,Supplier supplier){
		supplier.setOrgName(dto.getOrgName());
		supplier.setOfficeFax(dto.getOfficeFax());
		supplier.setOfficePhone(dto.getOfficePhone());
		supplier.setEmail(dto.getEmail());
		supplier.setAddress(dto.getAddress());
	}
	/**
	 * 保存（添加） 供应商信息
	 * 
	 * @param dto
	 *            机构DTO：SupplierDTO
	 */
	@Transactional()
	public void saveSupplier(SupplierDTO dto) {
		Supplier supplier = new Supplier();
		dto2entity(dto, supplier);
		if (dto.getCompanyNo() != null) {
			Company company = companyDAO.findById(dto.getCompanyNo());
			supplier.setParentOrg(company);
			supplier.setCompanyNo(dto.getCompanyNo());
		}
		supplierDAO.save(supplier);
		dto.setOrgNo(supplier.getOrgNo());
	}

	/**
	 * 修改供应商信息
	 * 
	 * @param dto
	 *            供应商DTO：SupplierDTO
	 */
	@Transactional()
	public void mergeSupplier(SupplierDTO dto) {
		Supplier supplier = supplierDAO.findById(dto.getOrgNo());
		dto2entity(dto, supplier);
		supplierDAO.merge(supplier);
	}

	/**
	 * 保存（添加） 供应商信息
	 * 
	 * @param dto
	 *            机构DTO：OrganizationDTO
	 */
	@Transactional
	public void saveSupplier(OrganizationDTO dto) {
		Supplier supplier = new Supplier();
		dto2entity(dto, supplier);
		supplierDAO.save(supplier);
	}

	/**
	 * dto to entity
	 * @param dto
	 * @param supplier
	 */
	private void dto2entity(OrganizationDTO dto,Supplier supplier){
		supplier.setOrgName(dto.getOrgName());
		supplier.setOfficeFax(dto.getOfficeFax());
		supplier.setOfficePhone(dto.getOfficePhone());
		supplier.setEmail(dto.getEmail());
		supplier.setAddress(dto.getAddress());

		if (dto.getParentOrgNo() != -1) {
			supplier.setParentOrg(companyDAO.findById(dto.getParentOrgNo()));
		}

	}
	/**
	 * 修改供应商信息
	 * 
	 * @param dto
	 *            机构DTO：SupplierDTO
	 */
	@Transactional
	public void mergeSupplier(OrganizationDTO dto) {
		Supplier supplier = supplierDAO.findById(dto.getOrgNo());
		dto2entity(dto, supplier);
		supplierDAO.merge(supplier);
	}

	/**
	 * 根据ID删除供应商
	 * 
	 * @param orgNo
	 *            供应商编号：Long orgNo
	 */
	@Transactional
	public void deleteSupplier(Long orgNo) {
		supplierDAO.delete(supplierDAO.findById(orgNo));
	}

	/**
	 * 批量删除供应商
	 * 
	 * @param orgNo
	 *            长整型数组：Long[] orgNo
	 */
	@Transactional()
	public void deleteSupplier(Long[] orgNo) {
		supplierDAO.deleteByIds(orgNo);
	}

	/**
	 * 根据ID查找供应商信息
	 * 
	 * @param id
	 *            供应商ID:Long id
	 */
	public Supplier findSupplierById(Long id) {
		return supplierDAO.findById(id);
	}

	/**
	 * 根据ID查找供应商DTO
	 * 
	 * @param id
	 *            供应商ID:Long id return SupplierDTO
	 */
	@Transactional
	public SupplierDTO findById(Long id) {
		SupplierDTO dto = new SupplierDTO();
		Supplier entity = supplierDAO.findById(id);
		if (entity != null) {
			SupplierDTO.entity2dto(entity, dto);
		}
		if (entity != null && entity.getParentOrg() != null) {
			dto.setCompanyNo(entity.getParentOrg().getOrgNo());
		}

		return dto;
	}

	/**
	 * 导出供应商
	 * 
	 * @param queryDTO
	 * @param sidx
	 * @param sord
	 * @return InputStream
	 */
	@Transactional
	public InputStream exportSupplier(SupplierQueryDTO queryDTO, String sidx,
			String sord) {

		LanguageContent lc = LanguageContent.getInstance();
		List<String[]> data = new ArrayList<String[]>();
		data.add(new String[] { lc.getContent("common.id"),
				lc.getContent("label.belongs.client"),
				lc.getContent("label.supplier.supplierName"),
				lc.getContent("label.supplier.supplierPhone"),
				lc.getContent("label.supplier.supplierEmail"),
				lc.getContent("label.supplier.supplierAddress"),
				lc.getContent("label.supplier.supplierFax") });// 加入表头

		queryDTO.setStart(0);
		queryDTO.setLimit(100000);

		PageDTO p = supplierDAO.findPager(queryDTO, sidx, sord);

		if (p != null && p.getData() != null && p.getData().size() > 0) {
			int i = 1;
			List<Supplier> entities = p.getData();
			for (Supplier supplier : entities) {
				data.add(new String[] {
						i + "",
						companyDAO.findById(supplier.getCompanyNo())
								.getOrgName().toString(),
						supplier.getOrgName(), supplier.getOfficePhone(),
						supplier.getEmail(), supplier.getAddress(),
						supplier.getOfficeFax() });
				i++;
			}
		}

		StringWriter sw = new StringWriter();
		CSVWriter csvw = new CSVWriter(sw);
		csvw.writeAll(data);
		 
		byte[] bs = null;
		try {
			bs = sw.getBuffer().toString().getBytes("GBK");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		ByteArrayInputStream stream = null;
		if(bs!=null){
			stream = new ByteArrayInputStream(bs);
		}
		try {
			if (csvw != null) {
				csvw.flush();
				csvw.close();
			}
			if (sw != null) {
				sw.flush();
				sw.close();
			}
		} catch (IOException e) {
			LOGGER.error(e);
		}
		return stream;
	}

	/**
	 * 导入供应商
	 * 
	 * @param fileName
	 * @return import quantity
	 */
	@Transactional
	public Integer importSupplier(String fileName) {

		Integer result = null;
		try {
			String fileEncode = FileEncodeUtils.getFileEncode(new File(fileName));
			Reader rd = new InputStreamReader(new FileInputStream(fileName),
					fileEncode);// 以字节流方式读取数据
			CSVReader reader = new CSVReader(rd);
			String[] line = null;

			Integer count = 0;
			Company company = new Company();
			while ((line = reader.readNext()) != null) {

			    // 默认的line.length = 1
                // 空的就跳过
                if (line.length == 1) continue;
			    
				Supplier entity = new Supplier();

				if (line[0] != null)
					company = companyDAO.findUniqueBy("orgName",line[0].toString());
				if(company==null){
					company = companyDAO.findAll().get(0);
				}
				if ("company".equals(company.getOrgType()))
					entity.setCompanyNo(company.getOrgNo());
				else {
					result = -1;
				}
				Organization org = companyDAO.findById(company.getOrgNo());
				entity.setParentOrg(org);

				entity.setOrgName(line[1].toString());
				entity.setOfficePhone(line[2].toString());
				entity.setEmail(line[3].toString());
				entity.setAddress(line[4].toString());
				entity.setOfficeFax(line[5].toString());
				supplierDAO.save(entity);
				count++;
			}
			if(result == null)
				result = count;
		} catch (Exception e1) {
			LOGGER.error(e1);
			result = -2;
		}
		return result;
	}
}
